<?php
declare(strict_types=1);

namespace App\Service;

use App\Helper\HashHelper;
use App\Model\Contact\ContactApply;
use App\Model\User;
use App\Model\UsersOpenId;
use App\Repository\Article\ArticleClassRepository;
use App\Repository\UserRepository;
use Hyperf\DbConnection\Db;

class DouService extends BaseService
{
    /**
     * @var UserRepository
     */
    private $appId;
    private $secret;
    private $accessToken;

    /**
     * @var ArticleClassRepository
     */
    private $articleClassRepository;

    /**
     * 获取Redis连接
     *
     * @return mixed|\Redis
     */
    private function redis()
    {
        return redis();
    }

    public function __construct($appId, $secret)
    {
        $this->appId = $appId;
        $this->secret = $secret;

        $this->getAccessToken();
    }

    public function getAccessToken()
    {
        $this->accessToken = $this->redis()->get('DOU_ACCESS_TOKEN_' . $this->appId);

        if (empty($this->accessToken)) {
            $this->accessToken = $this->refreshToken();
            $this->redis()->set('DOU_ACCESS_TOKEN_' . $this->appId, $this->accessToken, 7100);
        }

    }

    /**
     * 刷新 access_token
     * @return mixed
     */
    public function refreshToken()
    {
        $url = 'https://developer.toutiao.com/api/apps/v2/token';
//        $url = 'https://sport.luojiweiye.com/api/system/callback';
        $params = [
            'grant_type' => 'client_credential',
            'appid'      => $this->appId,
            'secret'     => $this->secret,
        ];


        $client = new \GuzzleHttp\Client();

        $r = $client->post($url, ['headers' => ['Content-Type' => 'application/json'], 'json' => $params])->getBody()->getContents();

        info("刷新抖音接口 access_token 参数:", [$params, $r]);
        $accessToekn = data_get(json_decode($r, true), 'data.access_token', '');

        return $accessToekn;
    }

    /**
     * open登录逻辑
     */
    public function openLogin($code)
    {
        $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        $params = [
            'code'       => $code,
            'appid'      => $this->appId,
            'secret'     => $this->secret,
        ];

        $client = new \GuzzleHttp\Client();

        $r = $client->post($url, ['json' => $params])->getBody()->getContents();

        $j = json_decode($r, true);

        info('获取抖音openid', [$params, $r]);
        $openid = data_get($j, 'data.openid', '');
        if (empty($openid)) {
            throw new \Exception('获取抖音openid失败', 604);
        }

        $openUser = UsersOpenId::where('app_id', '=', $this->appId)->where('open_id', '=', $openid)->first();

        if (!empty($openUser)) {
            $updata = [];
            if (data_get($openUser, 'user_id', 0) == 0) {
                $user = User::create([
                    'name' => str_random(10),
                    'password' => time(),
                    'api_token' => str_random(50),
                    'status'    => 0,
                ]);
                $login_type = 1;
                $updata['user_id'] = data_get($user, 'id');
            }
            UsersOpenId::where('app_id', '=', $this->appId)->where('open_id', '=', $openid)->update($updata);
            $user_id = data_get($openUser, 'user_id', '');
        } else {
            // 创建微信信息
            $user = User::create([
                'name' => str_random(10),
                'password' => time(),
                'api_token' => str_random(50),
                'status'    => 0,
            ]);
            $login_type = 1;
            $user_id = data_get($user, 'id', '');
            $data = [
                'app_id'  => $this->appId,
                'open_id' => $openid,
                'unionid' => '',
                'user_id' => $user_id,
            ];
            $openUser = UsersOpenId::create($data);
        }
//        $user = User::where('id', $user_id)->first();

        return $openUser;
    }
}
